import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getToken, removeToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

function exceptionHandle(error) {
  if (error.code === 'ECONNABORTED' && error.message.includes('timeout')) {
    Message({
      message: '您请求超时,请重试',
      type: 'error'
    })
  }
  const { response } = error
  if (response) {
    switch (response.status) {
      case 401: // Unauthorized
        removeToken()
        Message({
          message: '您登陆失效,请重新登陆',
          type: 'error',
          onClose: function() {
            // 只有在当前路由不是登录页面才跳转
            router.currentRoute.path !== 'login' &&
            router.replace({
              path: '/login',
              query: { redirect: router.currentRoute.path }
            })
          }
        })
        break
      case 403:// Forbidden
        Message({
          message: '您没有操作权限,请稍后再试',
          type: 'error'
        })
        break
      case 404:// Not found

        break
      case 422:// Unprocessable Entity
        Message({
          message: response.data && response.data.message || 'Unprocessable Entity',
          type: 'error'
        })
        break
      case 429:// Too Many Requests
        Message({
          message: '您请求太频繁,请稍后再试',
          type: 'error'
        })
        break
      case 500:
        Message({
          message: 'Internal Server Error',
          type: 'error'
        })
        break
    }
  } else {
    // 服务器没有返回结果
    if (!window.navigator.onLine) {
      // 断网处理
      Message({
        message: '您的网络开小差,请检查网络',
        type: 'warning'
      })
    }
  }
}

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    var token = response.headers.authorization
    if (token) {
      // 如果 header 中存在 token，那么触发 refreshToken 方法，替换本地的 token
      store.dispatch('user/refreshToken', token)
    }
    // if the custom code is not 1, it is judged as an error.
    if (res.code !== 1) {
      switch (res.code) {
        case 50008:// Invaild token
        case 50012:// Other clients logged in
        case 50014:// Token expired
          // to re-login
          MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
            confirmButtonText: 'Re-Login',
            cancelButtonText: 'Cancel',
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          })
          break
        default:
          Message({
            message: res.message || 'Error',
            type: 'error',
            duration: 2 * 1000
          })
          break
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    const { config } = error
    // If config does not exist or the retry option is not set, reject
    if (!config || !config.retry) {
      exceptionHandle(error)
      // Reject with the error
      return Promise.reject(error)
    }

    // Set the variable for keeping track of the retry count
    config.__retryCount = config.__retryCount || 0

    // Check if we've maxed out the total number of retries
    if (config.__retryCount >= config.retry) {
      exceptionHandle(error)
      // Reject with the error
      return Promise.reject(error)
    }

    // Increase the retry count
    config.__retryCount += 1

    // Create new promise to handle exponential backoff
    const backoff = new Promise(function(resolve) {
      setTimeout(function() {
        resolve()
      }, config.retryDelay || 1)
    })

    // Return the promise in which recalls axios to retry the request
    return backoff.then(function() {
      return axios(config)
    })
  }
)

export default service
